<template>
  <!-- 顶部美化工具栏 -->
  <el-affix>
    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="addChild">子节点</el-button>
      <el-button type="success" :icon="CirclePlus" @click="addSibling">同级节点</el-button>
      <el-button type="danger" :icon="Delete" @click="removeNode">删除</el-button>
      <el-button :icon="Refresh" @click="fitView">适应窗口</el-button>

      <el-divider direction="vertical" />

      <el-upload
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          accept=".json"
          :on-change="importJSON"
      >
        <el-button :icon="Upload">导入</el-button>
      </el-upload>
      <el-button :icon="Download" @click="exportJSON">导出</el-button>

      <el-divider direction="vertical" />

      <el-select v-model="currentTheme" style="width:120px;" @change="changeTheme">
        <el-option v-for="t in themes" :key="t" :label="t" :value="t" />
      </el-select>

      <el-input
          v-model="keyword"
          placeholder="搜索节点"
          style="width:160px;margin-left:8px;"
          @keyup.enter="search"
      >
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
    </div>
  </el-affix>

  <!-- 画布 -->
  <div ref="mindMapContainer" class="mind-map-container"></div>

  <!-- 右键菜单（仅当选中节点后右击才出现） -->
  <ContextMenu
      v-if="contextMenuVisible"
      :position="contextMenuPosition"
      :node="activeNode"
      @command="onContextMenu"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import MindMap from 'simple-mind-map'
import ContextMenu from './page/components/ContextMenu.vue'
import { ElMessage } from 'element-plus'
import {
  Plus, CirclePlus, Delete, Refresh, Upload, Download, Search
} from '@element-plus/icons-vue'

const mindMapContainer = ref(null)
let mindMap = null

/* ---------- 响应式数据 ---------- */
const keyword          = ref('')
const currentTheme     = ref('default')
const themes           = ref([
  'default','classic','minions','pinkGrape','mint','gold','vitalityOrange',
  'greenLeaf','dark2','skyGreen','classic2','classic3','classic4','classic5','dark3','dark4'
])
const contextMenuVisible  = ref(false)
const contextMenuPosition = ref({ x:0, y:0 })
const activeNode          = ref(null)

/* ---------- 生命周期 ---------- */
onMounted(async () => {
  mindMap = new MindMap({
    el: mindMapContainer.value,
    data: {
      data: { text: '根节点' },
      children: [
        {
          data: { text: '可折叠节点', expand: true },
          children: [
            { data: { text: '子节点 1' }, children: [] },
            { data: { text: '子节点 2' }, children: [] }
          ]
        }
      ]
    }
  })
  await loadPlugins()
  bindRightClick()
})

/* ---------- 插件加载 ---------- */
const pluginNames = ['Export', 'Drag', 'Keyboard', 'MiniMap']
async function loadPlugins() {
  for (const name of pluginNames) {
    try {
      const mod = await import(`simple-mind-map/src/plugins/${name}.js`)
      mindMap.addPlugin(mod.default)
    } catch (e) {
      console.warn(`插件 ${name} 加载失败`, e)
    }
  }
}

/* ---------- 工具栏 ---------- */
function addChild()   { mindMap.execCommand('INSERT_CHILD_NODE') }
function addSibling() { mindMap.execCommand('INSERT_NODE') }
function removeNode() { mindMap.execCommand('REMOVE_NODE') }
function fitView()    { mindMap.view.reset() }
function changeTheme(){ mindMap.setTheme(currentTheme.value) }
function search() {
  if (!keyword.value) return
  const nodes = mindMap.search.search(keyword.value)
  if (nodes.length) nodes[0].active()
  else ElMessage.info('未找到')
}
function exportJSON() {
  const blob = new Blob([JSON.stringify(mindMap.getData(), null, 2)], { type:'application/json' })
  const url  = URL.createObjectURL(blob)
  const a    = document.createElement('a')
  a.href = url; a.download = 'mindmap.json'; a.click(); URL.revokeObjectURL(url)
}
function importJSON(uploadFile) {
  const reader = new FileReader()
  reader.onload = () => {
    try { mindMap.setData(JSON.parse(reader.result)) }
    catch { ElMessage.error('JSON 格式错误') }
  }
  reader.readAsText(uploadFile.raw)
}

/* ---------- 右键菜单（仅当选中节点后右击） ---------- */
function bindRightClick() {
  mindMap.on('node_contextmenu', (e, node) => {
    e.preventDefault()
    mindMap.renderer.setNodeActive(node, true) // 确保选中
    activeNode.value = node
    contextMenuPosition.value = { x: e.clientX, y: e.clientY }
    contextMenuVisible.value  = true
  })
  mindMap.on('draw_click', () => (contextMenuVisible.value = false))
}

/* ---------- 右键菜单命令 ---------- */
function onContextMenu({ cmd }) {
  switch (cmd) {
    case 'addChild':   mindMap.execCommand('INSERT_CHILD_NODE'); break
    case 'addSibling': mindMap.execCommand('INSERT_NODE');       break
    case 'remove':     mindMap.execCommand('REMOVE_NODE');       break
    case 'edit':       mindMap.execCommand('EDIT_NODE');         break
    case 'expand':
    case 'collapse':
      activeNode.value.setData({ expand: cmd === 'expand' })
      activeNode.value.renderNode()   // 强制重绘
      break
    case 'layout':     mindMap.execCommand('LAYOUT_TOWARDS');    break
  }
  contextMenuVisible.value = false
}
</script>

<style scoped>
.toolbar {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: #ffffff;
  border-bottom: 1px solid #dcdfe6;
}
.mind-map-container {
  width: 100%;
  height: calc(100vh - 60px);
}
</style>